package com.zbar.lib;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Point;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.bull.BullXunjianActivity;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.model.GongNiuZiChan;
import com.zbar.lib.camera.CameraManager;
import com.zbar.lib.decode.CaptureActivityHandler;
import com.zbar.lib.decode.InactivityTimer;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;

/**
 * 作者: 陈涛(1076559197@qq.com)
 * <p>
 * 时间: 2014年5月9日 下午12:25:31
 * <p>
 * 版本: V_1.0.0
 * <p>
 * 描述: 扫描界面
 */
public class CaptureActivity extends Activity implements Callback,
        OnClickListener {
    private CaptureActivityHandler handler;
    private boolean hasSurface;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.50f;
    private boolean vibrate;
    private int x = 0;
    private int y = 0;
    private int cropWidth = 0;
    private int cropHeight = 0;
    private RelativeLayout mContainer = null;
    private RelativeLayout mCropLayout = null;
    private ImageView ivBack = null;
    private boolean isNeedCapture = false;
    //公牛新加
    private TextView shoudian, shoudongshuru;
    private ImageView close_bl;

    public boolean isNeedCapture() {
        return isNeedCapture;
    }

    public void setNeedCapture(boolean isNeedCapture) {
        this.isNeedCapture = isNeedCapture;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getCropWidth() {
        return cropWidth;
    }

    public void setCropWidth(int cropWidth) {
        this.cropWidth = cropWidth;
    }

    public int getCropHeight() {
        return cropHeight;
    }

    public void setCropHeight(int cropHeight) {
        this.cropHeight = cropHeight;
    }

    /**
     * Called when the activity is first created.
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if ("gongniu".equals(getIntent().getStringExtra("tag"))) {
            setContentView(R.layout.gongniuactivity_qr_scan);
            shoudian = (TextView) findViewById(R.id.shoudian);
            shoudongshuru = (TextView) findViewById(R.id.shoudongshuru);
            close_bl = (ImageView) findViewById(R.id.close_bl);
        } else {
            setContentView(R.layout.activity_qr_scan);
        }
        // 初始化 CameraManager
        CameraManager.init(getApplication());
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);

        mContainer = (RelativeLayout) findViewById(R.id.capture_containter);
        mCropLayout = (RelativeLayout) findViewById(R.id.capture_crop_layout);
        ivBack = (ImageView) findViewById(R.id.back);
        ivBack.setOnClickListener(this);

        ImageView mQrLineView = (ImageView) findViewById(R.id.capture_scan_line);
        TranslateAnimation mAnimation = new TranslateAnimation(
                TranslateAnimation.ABSOLUTE, 0f, TranslateAnimation.ABSOLUTE,
                0f, TranslateAnimation.RELATIVE_TO_PARENT, 0f,
                TranslateAnimation.RELATIVE_TO_PARENT, 0.9f);
        mAnimation.setDuration(1500);
        mAnimation.setRepeatCount(-1);
        mAnimation.setRepeatMode(Animation.REVERSE);
        mAnimation.setInterpolator(new LinearInterpolator());
        mQrLineView.setAnimation(mAnimation);

        addlistener();

    }

    private boolean isopent = false;
    private Camera camera;

    private void addlistener() {
        if (null != shoudongshuru && null != shoudian&&null!=close_bl) {
            shoudongshuru.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showClearLogin();
                }
            });
            shoudian.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    light();

                }
            });

            close_bl.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
        }
    }
    AlertDialog builder;
    //弹出dialog
    public void showClearLogin() {
        View view = LayoutInflater.from(CaptureActivity.this).inflate(R.layout.gongniu_dialog,
                null);
        builder = new AlertDialog.Builder(CaptureActivity.this).create();
        builder.setCancelable(true);
        builder.setView(view);
        final EditText btnPositive = (EditText) view.findViewById(R.id.dialog_description);
        final Button btnNegative = (Button) view.findViewById(R.id.dialog_negative);
        btnNegative.setEnabled(false);
        btnNegative.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
//					Toast.makeText(CaptureActivity.this,btnPositive.getText(),Toast.LENGTH_SHORT).show();
//                requestNumNo(btnNegative.getText().toString());
                requestNumNo(btnPositive.getText().toString());
                btnNegative.setEnabled(false);
            }
        });
        builder.show();
        btnPositive.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void afterTextChanged(Editable s) {
                if(btnPositive.getText().toString().length()>0){
                    btnNegative.setBackgroundColor(getColor(R.color.gongniulan));
                    btnNegative.setEnabled(true);
                }else{
                    btnNegative.setBackgroundColor(getColor(R.color.gongniuhui));
                    btnNegative.setEnabled(false);
                }
            }
        });
    }

    boolean flag = true;

    protected void light() {
        if (flag == true) {
            flag = false;
            // 开闪光灯
            CameraManager.get().openLight();
        } else {
            flag = true;
            // 关闪光灯
            CameraManager.get().offLight();
        }

    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.capture_preview);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    public void handleDecode(String result) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String strSend = "";
        if (!TextUtils.isEmpty(result)) {
            try {
                strSend = new String(result.getBytes(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Intent intent = getIntent();
            intent.putExtra("result", strSend);
            Log.d("erweima", "从这里开始传递" + strSend);
            if("gongniu".equals(getIntent().getStringExtra("tag"))) {
                requestNumNo(strSend);
            }else {
                setResult(RESULT_OK, intent);
                CaptureActivity.this.finish();
            }
        }

    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);

            Point point = CameraManager.get().getCameraResolution();
            int width = point.y;
            int height = point.x;

            int x = mCropLayout.getLeft() * width / mContainer.getWidth();
            int y = mCropLayout.getTop() * height / mContainer.getHeight();

            int cropWidth = mCropLayout.getWidth() * width
                    / mContainer.getWidth();
            int cropHeight = mCropLayout.getHeight() * height
                    / mContainer.getHeight();

            setX(x);
            setY(y);
            setCropWidth(cropWidth);
            setCropHeight(cropHeight);
            // 设置是否需要截图
            setNeedCapture(true);

        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(CaptureActivity.this);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public Handler getHandler() {
        return handler;
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.back:
                CaptureActivity.this.finish();
                break;
            default:
                break;
        }
    }

    public String ssmendian;
    public String tfdz;
    public String name1;
    public String zcmc;
    public String zclx;


    public void requestNumNo(final String name) {

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "cquery");
        params.addBodyParameter("objectApiName", "yxzc");
        params.addBodyParameter("expressions", "name=" + "'" + name + "'");
        Log.d("列表值url-------------------------", UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getLookupValue"
                + "&objectId=2016360343BD7B2SQ2PO" + "&pageSize=1"
                + "&keyword=");
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        Log.d("列表值接口失败-------------------------", arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        Log.d("列表值接口成功-------------------------", arg0.result);
                        Gson gson = new Gson();
                        GongNiuZiChan mData = gson.fromJson(arg0.result.toString(),
                                GongNiuZiChan.class);
                        if (mData.data.size() <= 0) {
                            Toast.makeText(CaptureActivity.this, "该编码不存在", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            mData.data.get(0);
                            ssmendian = mData.data.get(0).ssmendianccname;
                            tfdz = mData.data.get(0).tfdz;
                            name1 = mData.data.get(0).name;
                            zcmc = mData.data.get(0).zcmc;
                            zclx = mData.data.get(0).zclx;

                            requestNum(name,mData);
                        }
                    }
                });
    }

    public void requestNum(String name, final GongNiuZiChan mDatax) {

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "cqueryWithRoleRight");
        params.addBodyParameter("objectApiName", "yxzc");
        params.addBodyParameter("expressions", "name=" + "'" + name + "'");
        Log.d("列表值url-------------------------", UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&serviceName=getLookupValue"
                + "&objectId=2016360343BD7B2SQ2PO" + "&pageSize=1"
                + "&keyword=");
        Log.d("request", UrlManager.getInterfaceUrl() + "serviceName=cqueryWithRoleRight" + "objectApiName=yxzc" + "expressions=name="+"'"+name+"'" + "binding=" + RunTimeManager.getInstance()
                .getServerBinding());
        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {
                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        Log.d("列表值接口失败-------------------------", arg1);
                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        Log.d("列表值接口成功-------------------------", arg0.result);
                        Gson gson = new Gson();
                        GongNiuZiChan mData = gson.fromJson(arg0.result.toString(),
                                GongNiuZiChan.class);
                        if (mData.data.size() <= 0) {
                            Toast.makeText(CaptureActivity.this, "该资产无需巡检", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            if (null == mData.data.get(0).ssjxsccname || "".equals(mData.data.get(0).ssjxsccname)) {
                                Toast.makeText(CaptureActivity.this, "该资产无需巡检", Toast.LENGTH_SHORT).show();
                                finish();
                            } else {
                                Intent intent = new Intent(CaptureActivity.this, BullXunjianActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("gongniudata", (Serializable) mDatax.data.get(0));
                                intent.putExtras(bundle);
//                                intent.putExtra("ssmendian",ssmendian);
//                                intent.putExtra("tfdz",tfdz);
//                                intent.putExtra("name1",name1);
//                                intent.putExtra("zcmc",zcmc);
//                                intent.putExtra("zclx",zclx);
                                intent.putExtra("ssjxs",mData.data.get(0).ssjxsccname);
                                startActivity(intent);
                                finish();
                            }
                        }
                    }
                });
    }
}